package ui;

import dao.StudentScholarshipDao;
import dao.TeacherApplicationDao;
import model.Teacher;
import model.TeacherApplication;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.List;

public class TeacherMainFrame extends JFrame {
    private Teacher teacher;

    private JTextField scholarshipNameField;
    private JTextArea scholarshipReqArea;
    private JButton publishBtn;

    private JTable applicationTable;
    private DefaultTableModel tableModel;
    private JButton approveBtn;
    private JButton rejectBtn;

    private StudentScholarshipDao scholarshipDao = new StudentScholarshipDao();
    private TeacherApplicationDao applicationDao = new TeacherApplicationDao();

    public TeacherMainFrame(Teacher teacher) {
        this.teacher = teacher;
        setTitle("教师主界面 - 欢迎 " + teacher.getName());
        setSize(900, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        Font defaultFont = new Font("微软雅黑", Font.PLAIN, 14);
        Color lightPink = new Color(255, 240, 250);
        Color buttonPink = new Color(255, 105, 180);

        JPanel topBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        topBar.setBackground(lightPink);
        JButton backBtn = new JButton("返回主界面");
        styleButton(backBtn, buttonPink);
        backBtn.addActionListener(e -> {
            dispose();
            Main.showMainMenu();
        });
        topBar.add(backBtn);

        JTabbedPane tabbedPane = new JTabbedPane();

        JPanel publishPanel = new JPanel(new BorderLayout());
        publishPanel.setBackground(lightPink);
        JPanel centerPanel = new JPanel(new GridBagLayout());
        centerPanel.setBackground(lightPink);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 10, 8, 10);
        gbc.anchor = GridBagConstraints.CENTER;

        gbc.gridx = 0; gbc.gridy = 0;
        JLabel nameLabel = new JLabel("奖学金名称:");
        nameLabel.setFont(defaultFont);
        centerPanel.add(nameLabel, gbc);

        scholarshipNameField = new JTextField();
        scholarshipNameField.setPreferredSize(new Dimension(300, 30));
        scholarshipNameField.setFont(defaultFont);
        gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL;
        centerPanel.add(scholarshipNameField, gbc);

        gbc.gridx = 0; gbc.gridy = 1;
        gbc.fill = GridBagConstraints.NONE;
        JLabel reqLabel = new JLabel("申报要求:");
        reqLabel.setFont(defaultFont);
        centerPanel.add(reqLabel, gbc);

        scholarshipReqArea = new JTextArea(8, 20);
        scholarshipReqArea.setLineWrap(true);
        scholarshipReqArea.setWrapStyleWord(true);
        scholarshipReqArea.setFont(defaultFont);
        scholarshipReqArea.setBorder(BorderFactory.createLineBorder(buttonPink, 1));
        scholarshipReqArea.setBackground(Color.WHITE);
        gbc.gridx = 1; gbc.fill = GridBagConstraints.BOTH;
        centerPanel.add(new JScrollPane(scholarshipReqArea), gbc);

        publishBtn = new JButton("发布");
        styleButton(publishBtn, buttonPink);
        gbc.gridx = 1; gbc.gridy = 2; gbc.fill = GridBagConstraints.NONE;
        centerPanel.add(publishBtn, gbc);
        publishBtn.addActionListener(e -> publishScholarship());

        publishPanel.add(centerPanel, BorderLayout.CENTER);

        JPanel bottomButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton updateBtn = new JButton("修改奖学金");
        JButton deleteBtn = new JButton("撤销奖学金");
        styleButton(updateBtn, buttonPink);
        styleButton(deleteBtn, buttonPink);
        bottomButtonPanel.add(updateBtn);
        bottomButtonPanel.add(deleteBtn);
        updateBtn.addActionListener(e -> updateScholarship());
        deleteBtn.addActionListener(e -> deleteScholarship());
        publishPanel.add(bottomButtonPanel, BorderLayout.SOUTH);

        JPanel reviewPanel = new JPanel(new BorderLayout(10, 10));
        reviewPanel.setBackground(lightPink);

        tableModel = new DefaultTableModel(new String[]{"申请ID", "学生ID", "姓名", "奖学金", "申请理由", "状态", "附件"}, 0) {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        applicationTable = new JTable(tableModel);
        applicationTable.setFont(defaultFont);
        applicationTable.setRowHeight(40);

        applicationTable.getColumnModel().getColumn(4).setCellRenderer((table, value, isSelected, hasFocus, row, column) -> {
            JTextArea textArea = new JTextArea();
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            textArea.setFont(table.getFont());
            textArea.setText(value == null ? "" : value.toString());
            textArea.setEditable(false);
            textArea.setOpaque(true);
            textArea.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
            return textArea;
        });

        applicationTable.getColumnModel().getColumn(6).setCellRenderer((table, value, isSelected, hasFocus, row, column) -> {
            JLabel label = new JLabel();
            label.setHorizontalAlignment(SwingConstants.CENTER);
            label.setText(value == null || value.toString().trim().isEmpty() ? "无附件" : "<html><u><font color='blue'>查看</font></u></html>");
            label.setFont(defaultFont);
            label.setOpaque(isSelected);
            label.setBackground(isSelected ? table.getSelectionBackground() : null);
            return label;
        });

        applicationTable.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int row = applicationTable.rowAtPoint(e.getPoint());
                int col = applicationTable.columnAtPoint(e.getPoint());
                if (col == 6 && row >= 0) {
                    String filePath = (String) tableModel.getValueAt(row, col);
                    if (filePath == null || filePath.trim().isEmpty()) {
                        JOptionPane.showMessageDialog(TeacherMainFrame.this, "该申请无附件");
                        return;
                    }
                    try {
                        File file = new File(filePath);
                        if (!file.exists()) throw new Exception("文件不存在");
                        if (!Desktop.isDesktopSupported()) throw new Exception("系统不支持打开文件");
                        Desktop.getDesktop().open(file);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(TeacherMainFrame.this, "打开附件失败：" + ex.getMessage());
                    }
                }
            }
        });

        JScrollPane scrollTable = new JScrollPane(applicationTable);
        reviewPanel.add(scrollTable, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 10));
        approveBtn = new JButton("同意通过");
        styleButton(approveBtn, buttonPink);
        approveBtn.addActionListener(e -> batchReview("通过"));
        rejectBtn = new JButton("拒绝通过");
        styleButton(rejectBtn, buttonPink);
        rejectBtn.addActionListener(e -> batchReview("未通过"));
        buttonPanel.add(approveBtn);
        buttonPanel.add(rejectBtn);
        reviewPanel.add(buttonPanel, BorderLayout.SOUTH);

        ScholarshipViewPanel viewPanel = new ScholarshipViewPanel();
        JPanel scholarshipPanel = new JPanel(new BorderLayout());
        JButton refreshBtn = new JButton("刷新");
        styleButton(refreshBtn, buttonPink);
        refreshBtn.addActionListener(e -> viewPanel.refreshScholarships());
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        topPanel.add(refreshBtn);
        scholarshipPanel.add(topPanel, BorderLayout.NORTH);
        scholarshipPanel.add(viewPanel, BorderLayout.CENTER);

        tabbedPane.add("发布奖学金", publishPanel);
        tabbedPane.add("申报管理", reviewPanel);
        tabbedPane.add("奖学金查看", scholarshipPanel);

        add(topBar, BorderLayout.NORTH);
        add(tabbedPane, BorderLayout.CENTER);

        loadApplications();
        setVisible(true);
    }

    private void publishScholarship() {
        String name = scholarshipNameField.getText().trim();
        String requirement = scholarshipReqArea.getText().trim();
        if (name.isEmpty() || requirement.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写完整的奖学金信息");
            return;
        }
        boolean success = scholarshipDao.addScholarship(new model.StudentScholarship(name, requirement));
        if (success) {
            JOptionPane.showMessageDialog(this, "奖学金发布成功");
            scholarshipNameField.setText("");
            scholarshipReqArea.setText("");
            loadApplications();
        } else {
            JOptionPane.showMessageDialog(this, "奖学金发布失败（可能已存在）");
        }
    }

    private void updateScholarship() {
        String name = scholarshipNameField.getText().trim();
        String newRequirement = scholarshipReqArea.getText().trim();
        if (name.isEmpty() || newRequirement.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入要修改的奖学金名称和新的申报要求");
            return;
        }
        boolean updated = scholarshipDao.updateByName(name, newRequirement);
        if (updated) {
            JOptionPane.showMessageDialog(this, "修改成功！");
        } else {
            JOptionPane.showMessageDialog(this, "修改失败，可能该奖学金不存在");
        }
    }

    private void deleteScholarship() {
        String name = scholarshipNameField.getText().trim();
        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入要撤销的奖学金名称");
            return;
        }
        int confirm = JOptionPane.showConfirmDialog(this, "确定要撤销奖学金 '" + name + "' 吗？", "确认撤销", JOptionPane.YES_NO_OPTION);
        if (confirm != JOptionPane.YES_OPTION) return;
        boolean deleted = scholarshipDao.deleteByName(name);
        if (deleted) {
            JOptionPane.showMessageDialog(this, "奖学金已撤销");
            scholarshipNameField.setText("");
            scholarshipReqArea.setText("");
        } else {
            JOptionPane.showMessageDialog(this, "撤销失败，可能该奖学金不存在");
        }
    }

    private void loadApplications() {
        tableModel.setRowCount(0);
        List<TeacherApplication> apps = applicationDao.getAllApplications();
        for (TeacherApplication app : apps) {
            tableModel.addRow(new Object[]{
                    app.getId(),
                    app.getStudentId(),
                    app.getStudentName(),
                    app.getScholarshipName(),
                    app.getReason(),
                    app.getStatus(),
                    app.getFilePath()
            });
        }
        adjustRowHeights();
    }

    private void adjustRowHeights() {
        for (int row = 0; row < applicationTable.getRowCount(); row++) {
            int maxHeight = applicationTable.getRowHeight();

            for (int column = 0; column < applicationTable.getColumnCount(); column++) {
                TableCellRenderer cellRenderer = applicationTable.getCellRenderer(row, column);
                Component comp = applicationTable.prepareRenderer(cellRenderer, row, column);
                maxHeight = Math.max(maxHeight, comp.getPreferredSize().height);
            }

            if (applicationTable.getRowHeight(row) != maxHeight) {
                applicationTable.setRowHeight(row, maxHeight);
            }
        }
    }


    private void batchReview(String status) {
        int[] selectedRows = applicationTable.getSelectedRows();
        if (selectedRows.length == 0) {
            JOptionPane.showMessageDialog(this, "请选择要处理的申请");
            return;
        }
        for (int row : selectedRows) {
            int appId = (int) tableModel.getValueAt(row, 0);
            applicationDao.updateStatus(appId, status);
        }
        JOptionPane.showMessageDialog(this, "已标记为 " + status);
        loadApplications();
    }

    private void styleButton(JButton btn, Color color) {
        btn.setBackground(color);
        btn.setForeground(Color.WHITE);
        btn.setFont(new Font("微软雅黑", Font.BOLD, 14));
        btn.setFocusPainted(false);
        btn.setBorder(BorderFactory.createLineBorder(color.darker(), 1));
    }
}